package tcc.wa.persistence.dao;

import tcc.wa.model.GeographicCoordinate;
import tcc.wa.model.Location;
import tcc.wa.persistence.dao.base.DAOBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Data access object class responsible for Location
 * persistence management.
 */
public class LocationDAO extends DAOBase {

	public LocationDAO(Context context) {
		super(context);
	}

	/**
	 * Saves a location.
	 *
	 * @param location location to be saved
	 */
	public void saveLocation(Location location) {
		SQLiteDatabase database = getWritableDatabase();
		database.delete(LOCATION_TABLE_NAME, null, null);
		ContentValues values = new ContentValues();
		values.put("city", location.getCity());
		values.put("state", location.getState());
		values.put("region", location.getRegion());
		values.put("country", location.getCountry());
		values.put("latitude", location.getGeographicCoordinate().getLatitude());
		values.put("longitude", location.getGeographicCoordinate().getLongitude());
		long locationId = database.insert(LOCATION_TABLE_NAME, null, values);
		location.setId(locationId);
		close();
	}

	/**
	 * Finds the last location.
	 *
	 * @return the last location
	 */
	public Location findLastLocation() {
		Location location = null;
		SQLiteDatabase database = getWritableDatabase();
		Cursor cursor = database.query(LOCATION_TABLE_NAME, null, null, null, null, null, "id DESC", "1");
		if (cursor.moveToFirst()) {
			location = new Location();
			location.setId(cursor.getLong(0));
			location.setCity(cursor.getString(1));
			location.setState(cursor.getString(2));
			location.setRegion(cursor.getString(3));
			location.setCountry(cursor.getString(4));
			location.setGeographicCoordinate(new GeographicCoordinate(cursor.getDouble(5), cursor.getDouble(6)));
		}
		close();
		return location;
	}
	
	/**
	 * Finds location by its id.
	 *
	 * @param locationId the location id
	 * @return the location
	 */
	public Location FindById(long locationId) {
		Location location = null;
		SQLiteDatabase database = getWritableDatabase();
		Cursor cursor = database.query(LOCATION_TABLE_NAME, null, "id = ?", new String[] { String.valueOf(locationId) }, null, null, null, "1");
		if (cursor.moveToFirst()) {
			location = new Location();
			location.setId(cursor.getLong(0));
			location.setCity(cursor.getString(1));
			location.setState(cursor.getString(2));
			location.setRegion(cursor.getString(3));
			location.setCountry(cursor.getString(4));
			location.setGeographicCoordinate(new GeographicCoordinate(cursor.getDouble(5), cursor.getDouble(6)));
		}
		close();
		return location;
	}
}